package indi.zhifa.study2024.common.auth.sharding;

import indi.zhifa.core.auth.util.ITokenUtil;
import indi.zhifa.core.common.util.SpringUtil;
import indi.zhifa.study2024.common.auth.token.AuthObject;
import indi.zhifa.study2024.common.auth.util.DatasourceSetUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.List;

@Slf4j
public class EnterpriseShardingAlgorithm implements StandardShardingAlgorithm<Long> {

    @Override
    public String getType() {
        return "ENTERPRISE-SHARDING"; // 自定义算法类型名称
    }

    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> shardingValue) {
        ITokenUtil tokenUtil = SpringUtil.getBean(ITokenUtil.class);
        String prompt = DatasourceSetUtil.getDbPrompt();
        if(StringUtils.hasText(prompt)){
            return prompt;
        }
        if(tokenUtil.hasTokenObject()){
            AuthObject authObject = tokenUtil.getAuthObject();
            return authObject.getDbCode();
        }
        return "ds0";
    }

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, RangeShardingValue<Long> shardingValue) {
        String prompt = DatasourceSetUtil.getDbPrompt();
        if(StringUtils.hasText(prompt)){
            return List.of(prompt);
        }
        ITokenUtil tokenUtil = SpringUtil.getBean(ITokenUtil.class);
        if(tokenUtil.hasTokenObject()){
            AuthObject authObject = tokenUtil.getAuthObject();
            return List.of(authObject.getDbCode());
        }
        return List.of("ds0");
    }
}
